<template>
    <div class="content">
        <el-card>
            <el-form class="form">
                <el-row>
                    <el-col :span="5">
                        <el-form-item label="产品信息">
                            <RiskEntryInput
                                :url="'/ledger/fundInfo/list/byUser/like?fundCodeOrName='"
                                @set-entry-data="getEntryslist"
                                :itemKey="'fundProductCode'"
                                :returnDatas="searchParams.codeAndName"
                                class="item"
                                style="display: inline-block"
                                :placeholder="'产品代码、产品简称'"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="募集方式">
                            <el-select v-model="searchParams.fundType1" size="mini" class="item" clearable filterable @change="changeFundType1">
                                <el-option v-for="(value, key) in FundType1" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="产品类型">
                            <el-select
                                v-model="searchParams.fundType2"
                                size="mini"
                                class="item"
                                clearable
                                filterable
                                multiple
                                collapse-tags
                                @focus="focusFundeType2"
                            >
                                <el-option v-for="(value, key) in FundType2" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5">
                        <el-form-item label="豁免情况">
                            <el-select v-model="searchParams.exemptStatusList" size="mini" class="item" clearable filterable multiple collapse-tags>
                                <el-option v-for="(value, key) in ExemptList" :key="key" :value="key" :label="value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label-width="0px">
                            <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                            <el-button size="mini" @click="handleBtn('loadout')">导出</el-button>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <div class="table">
            <RiskGrid
                ref="risk-grid"
                :tableData="tableData"
                :column="tableColumns"
                :paging="paging"
                v-loading="tableLoading"
                style="height: calc(100% - 60px)"
                @page-change="getTableData"
            >
                <template #fundOptStatus="row">
                    {{ fundOptStatusPojo[row.fundOptStatus] || '--' }}
                </template>
                <template #fundType1="row">
                    {{ FundType1[row.fundType1] || '--' }}
                </template>
                <template #fundType2="row">
                    {{ FUNDTYPE2[row.fundType2] || '--' }}
                </template>
                <template #beProductStock="row"> {{ row.beProductStock === '1' ? '√' : '--' }} </template>
                <template #beProductFund="row"> {{ row.beProductFund === '1' ? '√' : '--' }} </template>
                <template #beProductBond="row"> {{ row.beProductBond === '1' ? '√' : '--' }} </template>
                <template #inProductStock="row"> {{ row.inProductStock === '1' ? '√' : '--' }} </template>
                <template #inProductFund="row"> {{ row.inProductFund === '1' ? '√' : '--' }} </template>
                <template #inProductBond="row"> {{ row.inProductBond === '1' ? '√' : '--' }} </template>
                <template #remark="row">
                    {{ row.remark ? '...' : '--' }}
                </template>
                <template #operation="row">
                    <a href="javascript:;" @click="handleBtnRow('setting', row)">设置</a>
                    <a href="javascript:;" @click="handleBtnRow('record', row)">详情</a>
                </template>
            </RiskGrid>
        </div>
        <!-- 设置同日反向-->
        <yh-dialog
            drag
            title="设置"
            :visible.sync="formSettingVisible"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="700px"
            class="setting-form"
        >
            <el-row>
                <span>产品间</span>
                <br />
                <el-checkbox v-model="formParams.beProductStock" true-label="1" false-label="0" label="股票"></el-checkbox>
                <el-checkbox v-model="formParams.beProductFund" true-label="1" false-label="0" label="货币基金"></el-checkbox>
                <el-checkbox v-model="formParams.beProductBond" true-label="1" false-label="0" label="债券"></el-checkbox>
            </el-row>
            <el-row>
                <span>产品内</span>
                <br />
                <el-checkbox v-model="formParams.inProductStock" true-label="1" false-label="0" label="股票"></el-checkbox>
                <el-checkbox v-model="formParams.inProductFund" true-label="1" false-label="0" label="货币基金"></el-checkbox>
                <el-checkbox v-model="formParams.inProductBond" true-label="1" false-label="0" label="债券"></el-checkbox>
            </el-row>

            <el-row>
                <span> 意见填写 </span>
                <el-input type="textarea" :rows="4" resize="none" size="mini" placeholder="请输入审批意见及记录信息" v-model="formParams.remark">
                </el-input>
            </el-row>
            <div slot="footer" class="dialog-footer">
                <el-button @click="formSettingVisible = false"> 取 消 </el-button>
                <el-button type="primary" @click="handleBtnDialog('setting-confirm')"> 确 认 </el-button>
            </div>
        </yh-dialog>

        <yh-dialog drag title="操作记录" :visible.sync="recordVisible" :close-on-click-modal="false" :close-on-press-escape="false" width="700px">
            <div>
                <el-timeline :reverse="false">
                    <el-timeline-item
                        v-for="(item, index) in recordsData"
                        :key="index"
                        :timestamp="item.modifyDateTime"
                        placement="top"
                        :hide-timestamp="true"
                    >
                        <span>
                            {{ showDate(item.modifyDateTime) + ' ' + item.operateNo }}
                        </span>
                        <br />
                        <div class="timeline-content">
                            <div v-for="(itme, index) in item.editDatas" :key="index" class="diff-text">
                                <!-- <div v-show="itme.riskModifyTypeEnum == '1'">
                                    <span>新增：</span> <span>{{ itme.moduleDetail }}</span>
                                    <span>
                                        {{ isNaN(itme.afterChange) ? itme.afterChange : numberFormat(itme.afterChange) }}
                                    </span>
                                </div> -->
                                <div v-if="itme.riskModifyTypeEnum == '2'">
                                    <span>{{ itme.moduleDetail }} -</span>
                                    <!-- <span>{{ isNaN(itme.beforeChange) ? itme.beforeChange : numberFormat(itme.beforeChange) }}</span>
                                    -> -->

                                    <span>
                                        {{ isNaN(itme.afterChange) ? itme.afterChange : numberFormat(itme.afterChange) }}
                                    </span>
                                </div>
                                <!-- <div v-show="itme.riskModifyTypeEnum == '3'">
                                    <span>删除：</span> <span>{{ itme.moduleDetail }}</span>
                                    <span>
                                        {{ isNaN(itme.beforeChange) ? itme.beforeChange : numberFormat(itme.beforeChange) }}
                                    </span>
                                </div> -->
                            </div>
                            <span>
                                {{ item.remark }}
                            </span>
                        </div>
                    </el-timeline-item>
                </el-timeline>
            </div>
            <div slot="footer" class="dialog-footer">
                <!-- TODO -->
                <el-button @click="recordVisible = false"> 取 消 </el-button>
                <el-button type="primary" @click="handleBtnDialog('record-confirm')"> 确 认 </el-button>
            </div>
        </yh-dialog>
    </div>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskGrid from '@/common/components/risk-grid.vue';
import { PageVO } from '@/common/vo';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import DictionConstUtil from '../dict';
import { SameDayReserveDTO, SameDayReserveVO } from '../vo/fund-ledger-manage';
import { getsameDayReverseRecords, sameDayReverseList, sameDayReverseSetting } from '../api/fund-ledger-manage';
import { downLoadFile } from '@/utils/request';
import EntryItemCompare from '@/pages/setting/components/item-setting/item-compare.vue';
import { numberFormat } from '@/utils/tools';
import moment from 'moment';

@Component({ name: 'SameDayReverse', components: { RiskEntryInput, RiskGrid, EntryItemCompare } })
export default class SameDayReverse extends Vue {
    numberFormat = numberFormat;
    Dict = new DictionConstUtil();
    fundOptStatusPojo = DictionConstUtil.fundOptStatusPojo;
    FundType2 = {};
    FUNDTYPE2 = DictionConstUtil.FUNDTYPE2;
    FundType1 = DictionConstUtil.FundType1;
    ExemptList = DictionConstUtil.ExemptList;
    // 分发配置参数
    searchParams: SameDayReserveDTO = {
        codeAndName: '',
        fundType1: '',
        fundType2: [],
        exemptStatusList: [],
    };

    tableColumns: any[] = [
        // {
        //     type: 'checkbox',
        //     fixed: 'left',
        //     align: 'center',
        //     width: 60,
        // },
        {
            title: '序号',
            type: 'seq',
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        { minWidth: '80px', field: 'fdProductCode', title: '产品代码', slots: { default: 'default' } },
        { minWidth: '160px', field: 'fundNameSt', title: '产品简称', slots: { default: 'default' } },
        { minWidth: '100px', field: 'fundOptStatus', title: '产品状态', align: 'center', slots: { default: 'operation' } },
        { minWidth: '100px', field: 'fundType1', title: '募集方式', align: 'center', slots: { default: 'operation' } },
        { minWidth: '100px', field: 'fundType2', title: '产品类型', align: 'center', slots: { default: 'operation' } },
        {
            minWidth: '100px',
            field: 'fundsRoom',
            title: '产品间',
            align: 'center',
            children: [
                { minWidth: '100px', field: 'beProductStock', title: '股票', align: 'center', slots: { default: 'operation' } },
                { minWidth: '100px', field: 'beProductFund', title: '货币基金', align: 'center', slots: { default: 'operation' } },
                { minWidth: '100px', field: 'beProductBond', title: '债券', align: 'center', slots: { default: 'operation' } },
            ],
        },

        {
            minWidth: '100px',
            field: 'fundsIn',
            title: '产品内',
            align: 'center',
            slots: { default: 'default' },
            children: [
                { minWidth: '100px', field: 'inProductStock', title: '股票', align: 'center', slots: { default: 'operation' } },
                { minWidth: '100px', field: 'inProductFund', title: '货币基金', align: 'center', slots: { default: 'operation' } },
                { minWidth: '100px', field: 'inProductBond', title: '债券', align: 'center', slots: { default: 'operation' } },
            ],
        },
        { minWidth: '140px', field: 'remark', title: '审批意见及记录', align: 'center', slots: { default: 'operation' } },
        {
            title: '操作',
            field: 'operation',
            fixed: 'right',
            width: 120,
            align: 'center',
            slots: { default: 'operation' },
        },
    ];

    paging: PageVO = {
        total: 0,
        currentPage: 0,
        pageSize: 25,
    };
    tableData: SameDayReserveVO[] = [
        {
            fdProductCode: '123',
            fundNameSt: '基金简称',
            fundOptStatus: '产品状态',
            fundType1: '募集方式',
            fundType2: '产品类型',
            beProductStock: '0',
            beProductFund: '0',
            beProductBond: '1',
            inProductStock: '1',
            inProductFund: '1',
            inProductBond: '1',
            remark: '',
        },
    ];
    tableLoading: boolean = false;
    formSettingVisible: boolean = false;
    recordVisible: boolean = false;
    recordsData: any = [];
    formParams: any = {
        beProductStock: '',
        beProductFund: '',
        beProductBond: '',
        inProductStock: '',
        inProductFund: '',
        inProductBond: '',
        remark: '',
    };

    firstVisit: boolean = true; // 首次访问
    @Prop() activeValue: string;
    @Watch('activeValue', { immediate: true })
    async handleActiveValue(newData, oldData) {
        if (newData == 'same-day-reverse' && this.firstVisit) {
            this.firstVisit = false;
            this.getTableData();
        }
    }

    /**
     * 表格行按钮处理
     */
    handleBtnRow(type: string, row: any) {
        if (type == 'setting') {
            this.formSettingVisible = true;
            for (let key in this.formParams) {
                this.formParams[key] = row[key];
            }
            this.formParams.remark = '';
            this.formParams.fdProductCode = row.fdProductCode;
        } else if (type == 'record') {
            this.recordVisible = true;
            getsameDayReverseRecords(row.fdProductCode)
                .then((res: any) => {
                    this.recordsData = res.map((item: any) => {
                        let arr = [];
                        let operateDetail = JSON.parse(item.operateDetail);
                        if (operateDetail.length) {
                            let values = Object.values(operateDetail[0]);
                            values.filter(ele => {
                                arr = arr.concat(ele);
                            });
                            // 意见处理
                            item.editDatas = arr.filter(ele => {
                                if (ele.moduleDetail == '审批意见') {
                                    item.remark = ele.afterChange;
                                    return false;
                                }
                                return true;
                            });
                        }
                        // item.editDatas = arr;
                        return item;
                    });
                })
                .catch(() => {
                    // let res = [
                    //     {
                    //         modifyDateTime: '20230423101229',
                    //         operateNo: 'xxz',
                    //         remark: '审批意见',
                    //         operateDetail: JSON.stringify([
                    //             { a: [{ afterChange: '123', beforeChange: '234', moduleDetail: '建仓期', riskModifyTypeEnum: '2' }] },
                    //             { b: [{ afterChange: 'kk', beforeChange: 'oo', moduleDetail: 'name', riskModifyTypeEnum: '2' }] },
                    //         ]),
                    //     },
                    // ];
                    // this.recordsData = res.map((item: any) => {
                    //     let operateDetail = JSON.parse(item.operateDetail);
                    //     let arr = [];
                    //     if (operateDetail.length) {
                    //         const values = Object.values(operateDetail[0]);
                    //         console.log(values);
                    //         values.filter(ele => {
                    //             arr = arr.concat(ele);
                    //         });
                    //         // 意见处理
                    //         item.editDatas = arr.filter(ele => {
                    //             if (ele.moduleDetail == '审批意见') {
                    //                 item.remark = ele.afterChange;
                    //                 return false;
                    //             }
                    //             return true;
                    //         });
                    //     }
                    //     // item.editDatas = arr;
                    //     return item;
                    // });
                    // console.log(this.recordsData, '------------');
                });
        }
    }
    /**
     * 日期和时间
     */
    showDate(value: string) {
        let date = value.substring(0, 8);
        let realDate = moment(date, 'YYYYMMDD').format('YYYY-MM-DD');
        return realDate;
    }

    /**
     * 弹框按钮处理
     */
    handleBtnDialog(type: string) {
        if (type == 'setting-confirm') {
            sameDayReverseSetting(this.formParams).then(() => {
                this.yh_message_success('设置成功!');
                this.getTableData();
            });
            this.formSettingVisible = false;
        } else if (type == 'record-confirm') {
            this.recordVisible = false;
        }
    }

    /**
     * 操作行按钮
     */
    async handleBtn(type: string) {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData();
            this.$nextTick(() => {
                (this.$refs['risk-grid'] as any).resetCheckRowKeys();
            });
        } else if (type == 'loadout') {
            await downLoadFile({
                url: '/ledger/productReverse/export',
                method: 'post',
                data: this.searchParams,
            });
            this.$nextTick(() => {
                (this.$refs['risk-grid'] as any).resetCheckRowKeys();
            });
        }
    }

    /**
     * 表格内容
     */
    getTableData() {
        this.tableLoading = true;
        sameDayReverseList({ ...this.searchParams, paging: this.paging })
            .then((res: any) => {
                this.tableData = res?.list || [];
                this.paging.total = res.total || 0;
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 产品代码
     */
    getEntryslist(val: any) {
        this.searchParams.codeAndName = val;
    }
    // 募集方式变动
    changeFundType1(value) {
        this.searchParams.fundType2 = [];
        if (value == '') {
            this.FundType2 = {};
        } else if (value == 'D') {
            this.FundType2 = DictionConstUtil.FundType3;
        } else if (['A', 'B'].includes(value)) {
            this.FundType2 = DictionConstUtil.FundType2;
        }
    }
    // 产品类型变动
    focusFundeType2() {
        if (this.searchParams.fundType1 == '') {
            this.yh_message_warn('先选择募集方式!');
            return;
        }
    }
}
</script>
<style lang="scss" scoped>
.content {
    height: 100%;
    .form {
        .el-form-item {
            margin-bottom: 0px;
        }
    }
    .table {
        padding: 10px;
        margin-top: 10px;
        height: calc(100% - 110px);
        background-color: #fff;
    }
    .setting-form {
        .el-row {
            margin-bottom: 15px;
            span {
                display: inline-block;
                margin-bottom: 5px;
            }
        }
    }
    a {
        padding: 0 5px;
    }
    .dialog-footer {
        text-align: right;
        margin-right: 10px;
    }
    /deep/ .el-checkbox__input.is-checked + .el-checkbox__label {
        color: #575757;
    }

    .timeline-content {
        background-color: #f7f8fc;
        padding: 10px;
        .diff-text {
            color: #ba926f;
        }
    }
}
/deep/ .vxe-header--row:first-child .vxe-header--column {
    &:nth-child(7),
    &:nth-child(8) {
        .vxe-cell .vxe-cell--title {
            font-weight: 700;
        }
    }
}
/deep/ .el-timeline-item__node {
    background-color: #fff !important;
    border: 3px solid #ba926f;
}
/deep/ .el-select__tags-text {
    display: inline-block;
    max-width: 25px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}
/deep/ .el-tag__close.el-icon-close {
    top: -5px;
}
</style>
